package com.dmlll.controller;

import com.alibaba.fastjson.JSON;
import com.dmlll.VO.PersonalInformationVO;
import com.dmlll.VO.PersonalMessageVO;
import com.dmlll.pojo.*;
import com.dmlll.service.*;
import com.dmlll.utils.Upload;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
public class PersonalMessageController {
    @Autowired
    private NationService nationService;
    @Autowired
    private ProvinceService provinceService;
    @Autowired
    private CityService cityService;
    @Autowired
    private CountyService countyService;
    @Autowired
    private TownshipService townshipService;
    @Autowired
    private PersonalMessageService personalMessageService;

    @RequestMapping("/findPersonalMessageById")
    @ResponseBody
    public PersonalMessage findPersonalMessageById(Integer id){
        return personalMessageService.findPersonalMessageById(id);
    }

    @RequestMapping("/getPersonalInformation")
    @ResponseBody
    public Integer getPersonalInformation(PersonalMessage personalMessage,
                                         @RequestParam(value = "image", required = false) MultipartFile image) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if (!"".equals(personalMessage.getComeTimeStr()) && null != personalMessage.getComeTimeStr()) {
            try {
                personalMessage.setComeTime(sdf.parse(personalMessage.getComeTimeStr()));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if (null!=image&&null != image.getOriginalFilename()&&!"".equals(image.getOriginalFilename())) {
            try {
                String originalFilename = image.getOriginalFilename();
                String file = Upload.PATH + new SimpleDateFormat("yyyyMMdd").format(new Date()) + "\\" + originalFilename;
                File newFile = new File(file);
                System.out.println(file);
                personalMessage.setImg(file);
                if(!newFile.exists()){
                    newFile.mkdirs();
                }
                image.transferTo(new File(file));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        personalMessage.setSubmitTime(new Date());
        personalMessage.setAuditState(1);
        if(personalMessage.getId()!=null){
            personalMessageService.updateGetPersonalInformation(personalMessage);
        }else {
            personalMessageService.addPersonalMessage(personalMessage);
        }
        return personalMessage.getId();
    }

    @RequestMapping("updatePersonalInformation")
    @ResponseBody
    public Integer updatePersonalInformation(PersonalMessage personalMessage){
        return personalMessageService.updatePersonalInformation(personalMessage);
    }

    /**
     * 返回所有民族
     *
     * @return
     */
    @RequestMapping("loadAllNation")
    @ResponseBody
    public List<Nation> loadAllNation() {
        return nationService.loadAllNation();
    }

    /**
     * 返回所有省
     *
     * @return
     */
    @RequestMapping("loadAllProvince")
    @ResponseBody
    public List<Province> loadAllProvince() {
        return provinceService.selectProvince();
    }

    /**
     * 返回省的市
     *
     * @param province
     * @return
     */
    @RequestMapping("loadNowCityByProvince")
    @ResponseBody
    public List<City> loadNowCityByProvince(String province) {
        return cityService.selectCity(province);
    }

    /**
     * 查市的区
     *
     * @param city
     * @return
     */
    @RequestMapping("loadNowCountyByCity")
    @ResponseBody
    public List<County> loadNowCountyByCity(String city) {
        List<County> counties = countyService.selectCounty(city);
        return counties;
    }

    /**
     * 根据县查镇
     * @param county
     * @return
     */
    @RequestMapping("loadNowTownshipByCounty")
    @ResponseBody
    public List<Township> loadNowTownshipByCounty(String county) {
        return townshipService.selectTownship(county);
    }

    /**
     * 分页模糊查询登记信息管理
     * @param pageNum
     * @param countPage
     * @param search
     * @return
     */
    @RequestMapping("/loadPersonalInformation")
    @ResponseBody
    public PageInfo<PersonalMessageVO> loadPersonalInformation(@RequestParam(value = "pageNum",defaultValue = "1")Integer pageNum,
                                                           @RequestParam(value = "countPage",defaultValue = "5")Integer countPage,
                                                           String search,HttpSession session){
        Integer grade = ((PopulaceUser)session.getAttribute("user")).getAccountGrade()-1;
        System.out.println(grade);
        PageHelper.startPage(pageNum,countPage);
        List<PersonalMessageVO> personalMessageVOS = personalMessageService.loadPersonalInformation(search,grade);
        PageInfo<PersonalMessageVO> page = new PageInfo<>(personalMessageVOS);
        return page;
    }

    /**
     *  审核
     * @param ids
     * @param isTrue
     * @return
     */
    @RequestMapping("check")
    @ResponseBody
    public Integer check(HttpSession session,Integer[] ids,Integer isTrue, String reason){
        String userAccount = ((PopulaceUser) session.getAttribute("user")).getUserAccount();
        return personalMessageService.check(ids,isTrue,reason,userAccount);
    }
    /**
     * 审核结果展示
     * @param pageNum
     * @param countPage
     * @param userId
     * @return
     */
    @RequestMapping("loadPersonalInformationCheckShow")
    @ResponseBody
    public PageInfo<PersonalMessage> loadPersonalInformationCheckShow(@RequestParam(value = "pageNum",defaultValue = "1")Integer pageNum,
                                                                      @RequestParam(value = "countPage",defaultValue = "5")Integer countPage,Integer userId){
        PageHelper.startPage(pageNum,countPage);
        List<PersonalMessage> list = personalMessageService.loadPersonalInformationCheckShow(userId);
        return new PageInfo<>(list);
    }


    @RequestMapping("getSession")
    @ResponseBody
    public Integer getSession(HttpSession session){
        if(session.getAttribute("user")!=null) {
            Integer id = ((PopulaceUser) session.getAttribute("user")).getId();
            return id;
        }
        return -1;
    }
    @RequestMapping("getSessionGrade")
    @ResponseBody
    public Integer getSessionGrade(HttpSession session){
        if(session.getAttribute("user")!=null) {
            Integer grade = ((PopulaceUser) session.getAttribute("user")).getAccountGrade();
            return grade;
        }
        return -1;
    }
    @RequestMapping("getSessionTown")
    @ResponseBody
    public String getSessionTown(HttpSession session){
        String town = ((PopulaceUser) session.getAttribute("user")).getUserTown();
        return town;
    }
    @RequestMapping("getSessionCounty")
    @ResponseBody
    public String getSessionCounty(HttpSession session){
        String county = ((PopulaceUser) session.getAttribute("user")).getUserCounty();
        return county;
    }
    @RequestMapping("getSessionCity")
    @ResponseBody
    public String getSessionCity(HttpSession session){
        String city = ((PopulaceUser) session.getAttribute("user")).getUserCity();
        return city;
    }
    @RequestMapping("getSessionProvince")
    @ResponseBody
    public String getSessionProvince(HttpSession session){
        String province = ((PopulaceUser) session.getAttribute("user")).getUserProvince();
        return province;
    }
    @RequestMapping("downloadShowFile")
    public void downloadShowFile(String path, HttpServletResponse response) {
        int i = path.lastIndexOf("\\");
        String oldName = path.substring(i + 1);
        Upload.downloadFile(response, path, oldName);
    }

    /**
     * 图表
     * @param personalInformationVO
     * @return
     */
    @RequestMapping("getData")
    @ResponseBody
    public String getData(PersonalInformationVO personalInformationVO){
        List<BaseEntity> data = personalMessageService.getData(personalInformationVO);
        List<String> name = new ArrayList<>();
        List<Integer> value = new ArrayList<>();
        Map<String,Object> map = new HashMap<>();
        for (BaseEntity be : data) {
            name.add(be.getName());
            value.add(be.getValue());
        }
        map.put("name",name);
        map.put("value",value);
        return JSON.toJSONString(map);
    }
}
